<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Services\OrderService;
use App\Services\WechatPaymentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OrderController extends Controller
{
    protected $OrderService;
    public function __construct(OrderService $OrderService)
    {
        $this->OrderService = $OrderService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $title = $request->title;
        $pageSize = $request->pageSize ?: 10;
        $page = $request->page ?: 1;
        $skip = $page * $pageSize - $pageSize;

        $sql = $this->OrderService->get($title);
        $sql->where('user_id',Auth::user()->id);
        $total = $sql->count();
        $data = $sql->skip($skip)->take($pageSize)->orderBy('created_at','desc')->get();
        return response()->json(['code' => 200, 'message' => '操作成功','page'=>$page,'pageSize'=>$pageSize,'total'=>$total,'data'=>$data]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        $data = Order::find($request->id);
        return response()->json(['code' => 200, 'message' => '操作成功','data'=>$data]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $POSTONLY = Order::POSTONLY;
        $input = $request->only($POSTONLY);
        $input['user_id'] = Auth::user()->id;
        $data = $this->OrderService->insert($input);
        $wxPay = new WechatPaymentService();
        $data->url = $wxPay->createScanOrder($data->no,$data->amount,$data->title);
        return response()->json(['code' => 200, 'message' => '操作成功','data'=>$data]);
    }

}
